package com.example.jwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.security.Key;

/**
 * @author Kent HAN
 * @date 2022-03-09
 */
public class JwtDemo {
    public static void main(String[] args) {
        // 生成JWT
        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        // {"alg":"HS256"}, {"sub":"Joe"}
        String jws = Jwts.builder().setSubject("Joe").signWith(key).compact();
        System.out.println(jws);

        String jws2 = Jwts.builder().setSubject("James").signWith(key).compact();
        System.out.println(jws2);

        // 解析JWT
        Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jws);
        System.out.println(claimsJws);
        String username = claimsJws.getBody().getSubject();
        System.out.println(username);

        Jws<Claims> claimsJws2 = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jws2);
        System.out.println(claimsJws2);
        String username2 = claimsJws2.getBody().getSubject();
        System.out.println(username2);
    }
}
